import { loginAPI, userInfoAPI } from '@/api'
export default {
  namespaced: true,
  state: {
    token: null,
    likedeTime: 0,
    userInfo: {}
  },
  mutations: {
    SET_TOKEN(state, token) {
      state.token = token
    },
    REMOVE_TOKEN(state) {
      state.token = null
    },
    SET_USERINFO(state, userInfo) {
      state.userInfo = userInfo
    },
    REMOVE_USERINFO(state) {
      state.userInfo = {}
    },
    SET_likedeTime(state, time) {
      state.likedeTime = time
    }
  },
  actions: {
    async loginAction({ commit, dispatch }, data) {
      const res = await loginAPI(data)
      commit('SET_TOKEN', res.data.token)
      commit('SET_USERINFO', res.data)
      commit('SET_likedeTime', Date.now())
      dispatch('getUserInfo')
    },
    // 获取userInfo的action
    async getUserInfo({ state, commit }) {
      const { data } = await userInfoAPI(state.userInfo.userId)
      commit('SET_USERINFO', { ...state.userInfo, ...data })
    },
    logout({ commit }) {
      commit('REMOVE_TOKEN')
      commit('REMOVE_USERINFO')
    }
  }
}
